/**
 * 
 */
requirejs.config({
    baseUrl:'http://static.auoffice.com/static/js' ,
    waitSeconds: 0,
    paths: {
    	jquery:'libs/jquery.min',
    	validate:'libs/validate/jquery.validate.min',
        datatables: 'libs/dataTables/jquery.dataTables.min',
        btdatatables: 'libs/dataTables/dataTables.bootstrap.min',
        chosen:'libs/chosen/chosen.jquery',
        //plugins
        base: 'common/base',
    },
    shim: {
    	'validate': {
    		deps: ['jquery'],
    		exports: 'validate'
    	},
        'datatables': {
            deps: ['jquery'],
            exports: 'datatables'
        },
        'btdatatables': {
            deps: ['jquery'],
            exports: 'btdatatables'
        }, 
        'chosen': {
            deps: ['jquery'],
            exports: 'chosen'
        },
    }
});

require([
    'jquery',
 	'common/base',
 	'chosen',
 	'validate',
 	'datatables',
 	'btdatatables'
],function($,base) {
    var table = $("#data_table").DataTable({
        "searching": true,
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "deferRender": true,
        "ajax": {
            "url": '/funcresource/functional/list/',
            "type": "POST"
        },
        "columnDefs": [
            {
               "targets": 0,
               "data": null,
               "name": null,
               "searchable": false,
               "bSortable": false,
               "render": function (data, type, full) {
                   var html = '<input style="width:18px;height:18px" type="checkbox" name="functional_id" data-icon_id="'+full.icon_id+'" data-func_resource_id="'+full.func_resource_id+'" data-state="'+full.state+'" data-id="'+full.id+'"/>';
                   return html;
               }
            },
            {
                "targets": 1,
                "data": "name",
                "name": "name",
                "searchable": false,
                "bSortable": false
            },
            {
            	"targets": 2,
            	"data": "func_resource_name",
            	"name": "func_resource_name",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 3,
            	"data": "label_css",
            	"name": "label_css",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 4,
            	"data": "remark",
            	"name": "remark",
            	"searchable": false,
            	"bSortable": false
            },
            {
            	"targets": 5,
            	"data": null,
            	"name": null,
            	"searchable": false,
            	"bSortable": false,
            	"render": function (data, type, full) {
            		var html = '<p class="text-center">'+full.state_desc+'</p>';
            		return html;
            	}
            }
        ],
        "initComplete": function () {
            var api = this.api();
            var column = api.column(5);
            var select = $('<select class="form-control" id="_status"><option value="">--状态--</option></select>')
            .appendTo($(column.header()).empty() )
            .on( 'change', function (){
                var val = $.fn.dataTable.util.escapeRegex(
                    $(this).val()
                );
                $("#all").prop("checked",false);
                column.search( val ? '^'+val+'$' : '', true, false ).draw();
            });
            select.append(_state());
        },
        "oLanguage": {
            "sLengthMenu": '每页显示 _MENU_条 &nbsp;',
            "sZeroRecords": "没有找到符合条件的数",
            "sProcessing": "加载中...",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "木有记录",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "sSearch": "搜索：",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "«",
                "sNext": "»",
                "sLast": "尾页"
            }
        }
    });
    var _state = function() {
        return  '<option value="0">有效</option><option value="1">已停用</option><option value="9">删除</option>';
    }; 
    //datatables 行点击事件
    $("#data_table tbody").on('click','tr', function () {
    	var checked = $("td",this).find("input[type=checkbox]");
    	if ($(checked).is(':checked')){
    		$(checked).prop("checked",false);
    	}else{
    		$(checked).prop("checked",true);
    	}
    	var tr_len = $("#data_table tbody tr").find("input[type=checkbox]").length;
    	var check_len = $("#data_table tbody tr").find("input[type=checkbox]:checked").length;
    	if (tr_len == check_len){
    		$("#all").prop("checked",true);
    	}else{
    		$("#all").prop("checked",false);
    	}
    });
    
    //datatables 全选事件
    $("#all").click(function(){
    	if ($(this).is(':checked')){
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",true);
    	}else{
    		$("#data_table tbody tr").find("input[type=checkbox]").prop("checked",false);
    	}
    });
    //点击添加用户按钮
    $(".add").click(function(){
    	Add({});
    });
    $(".update").click(function(){
    	var len = $("[name=functional_id]:checked").length;
    	if (len != 1){
    		base.layui.alert("信息","请选择一行");
    		return;
    	}
    	var functional_id = $("[name=functional_id]:checked").attr("data-id");
    	var icon_id = $("[name=functional_id]:checked").attr("data-icon_id");
    	var func_resource_id = $("[name=functional_id]:checked").attr("data-func_resource_id");
    	var tr = $("[name=functional_id]:checked").closest("tr");
    	
    	var data ={
    		"functional_id":functional_id,
    		"icon_id":icon_id,
    		"func_resource_id":func_resource_id,
    		"name":tr.children().eq(1).text(),
    		"css_class":tr.children().eq(3).text(),
    		"remark":tr.children().eq(4).text(),
    	};
    	Add(data);
    });
    $(".delete").click(function(){
    	var len = $("[name=functional_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据");
    		return;
    	}
    	var _functional_ids = []
    	var is_valid = false;
    	$("[name=functional_id]:checked").each(function(){
    		if($(this).attr("data-state") != 0){
    			is_valid = true;
    			return false;
    		}
    		_functional_ids.push($(this).attr("data-id"));
    	});
    	if(is_valid){
    		base.layui.alert("提示信息","请选择有效的记录");
    		return;
    	}
    	base.layui.confirm('警告', '确认删除选中的记录',{"_functional_ids":_functional_ids}, _delCallback);
    });
    var _delCallback = function(arg){
    	base.services.post('funcresource', 'deleteFunctional', {"functional_ids":arg._functional_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			base.layui.alert("成功信息","删除成功",callback);
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
    $(".reopen").click(function(){
    	var len = $("[name=functional_id]:checked").length;
    	if (len <= 0){
    		base.layui.alert("信息","请选择数据");
    		return;
    	}
    	var _functional_ids = [];
    	var is_valid = false;
    	$("[name=functional_id]:checked").each(function(){
    		if($(this).attr("data-state") != 9){
    			is_valid = true;
    			return false;
    		}
    		_functional_ids.push($(this).attr("data-id"));
    	});
    	if(is_valid){
    		base.layui.alert("提示信息","请选择删除的记录");
    		return;
    	}
    	base.layui.confirm('警告', '确认重新开通选中的记录',{"_functional_ids":_functional_ids}, _reopenCallback);
    });
    var _reopenCallback = function(arg){
    	base.services.post('funcresource', 'reopenFunctional', {"functional_ids":arg._functional_ids.join(",")}, function(code, msg, data) {
    		if (code === base.services.CODE_SUCC) {
    			base.layui.alert("成功信息","重新开通成功",callback);
    		} else {
    			base.layui.alert("错误信息",msg);
    		}
    	});
    };
    
    var parent_layer;
    var Add = function(_data){
		var add_html = base.tpls("auoffice/funcresource/functional/add",_data);
		parent_layer = layer.open({
			type: 1,
			area : ['450px','420px'],
			skin: 'layui-layer-demo', //样式类名
			title: ['添加功能资源', 'font-weight: bold;'],
			closeBtn: 1, //不显示关闭按钮
			shift: 2,
			btn: ['提交','取消'],
			shadeClose: true, //开启遮罩关闭
			content: add_html,
			success: function (layero) {
			    var btn = layero.find('.layui-layer-btn');
			    btn.css('text-align', 'center');
				base.services.post('icon', 'iconAll', {}, function(code, msg, data) {
					var icon_html = '<option value="">--请选择图标--</option>';
					if (code === base.services.CODE_SUCC) {
						for (var icon in data.icons){
							icon_html += '<option value="'+data.icons[icon].id+'">'+data.icons[icon].name+'</option>';
						}
						$(".icon-select").html(icon_html);
						$(".icon-select").chosen({no_results_text: "没有匹配结果"});
						$(".chosen-container .chosen-drop .chosen-results").css("max-height","150px");
						if (_data){
							$(".icon-select").val(_data["icon_id"]);
							$(".icon-select").trigger("chosen:updated");
						}
					} else {
						$(".icon-select").html(icon_html);
					}
				});
				base.services.post('funcresource', 'funcResourceAll', {}, function(code, msg, data) {
					var funcresource_html = '<option value="">--请选择功能资源--</option>';
					if (code === base.services.CODE_SUCC) {
						for (var funcresource in data.funcresources){
							funcresource_html += '<option value="'+data.funcresources[funcresource].id+'">'+data.funcresources[funcresource].name+'</option>';
						}
						$(".func-resource-select").html(funcresource_html);
						$(".func-resource-select").chosen({no_results_text: "没有匹配结果"});
						$(".chosen-container .chosen-drop .chosen-results").css("max-height","150px");
						if (_data){
							$(".func-resource-select").val(_data["func_resource_id"]);
							$(".func-resource-select").trigger("chosen:updated");
						}
					} else {
						$(".func-resource-select").html(funcresource_html);
					}
				});
			},
			btn1:function(index ,layerp){
				$("#Form").submit();
			},
			btn2:function(index ,layero){
				layer.close(index);
			}
		});
		
		
		//表单验证
		$("#Form").validate({
			rules:{
				name:{//资源名称
					required:true,
					minlength:2,
					maxlength:16,
				},
				css_class:{
					required:true,
				},
				func_resource_id:{
					required:true,
				}
			},
			messages:{
				name:{
					required:"请输入功能名称",
					minlength:"功能名称长度为2-16个字符",
					maxlength:"功能名称长度为2-16个字符"
				},
				css_class:{
					required:"请输入标签class",
				},
				func_resource_id:{
					required:"请选择功能资源",
				}
			},
			submitHandler:function(){
				base.services.post('funcresource', 'saveFunctional', $("#Form").serialize(), function(code, msg, data) {
					if (code === base.services.CODE_SUCC) {
						base.layui.alert("成功信息","保存成功",callback);
					} else {
						base.layui.alert("错误信息",msg);
					}
				});
			}
		});
	}
	var callback = function(){
		if (parent_layer){
			layer.close(parent_layer);
		}
		table.draw();
	}
});